package net.entelijan.cobean.toggle;

import javax.swing.JToggleButton;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import net.entelijan.cobean.core.ICobean;
import net.entelijan.cobean.core.IInitializer;
import net.entelijan.cobean.core.impl.AbstractBoundPropertyValueComponentBean;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * TODO More detailed documentation
 * 
 * @param <T>
 *            The class of the value represented by the input field. Can be any
 *            java object as long as you use an appropriate converter.
 */
public class DefaultToggleInitializer implements IInitializer<ICobean<Boolean>> {

	@SuppressWarnings("unused")
	private static Log log = LogFactory.getLog(DefaultToggleInitializer.class);

	private JToggleButton coToggleButton;

	public DefaultToggleInitializer() {
		super();
	}

	@Override
	public ICobean<Boolean> initialize() {
		final BooleanCobean re = new BooleanCobean();

		if (coToggleButton == null) {
			throw new IllegalStateException(
					"The property 'coToggleButton' is mandatory");
		}
		coToggleButton.addChangeListener(new ChangeListener() {

			@Override
			public void stateChanged(ChangeEvent e) {
				re.setValue(coToggleButton.isSelected());
			}
		});
		return re;
	}

	private class BooleanCobean extends
			AbstractBoundPropertyValueComponentBean<Boolean> {

		private Boolean value = Boolean.FALSE;

		@Override
		protected Boolean getValuePlain() {
			return value;
		}

		@Override
		protected void setValuePlain(Boolean value) {
			this.value = value;
			coToggleButton.setSelected(value);
		}

	}

	public JToggleButton getCoToggleButton() {
		return coToggleButton;
	}

	public void setCoToggleButton(JToggleButton coToggleButton) {
		this.coToggleButton = coToggleButton;
	}

}
